package com.zy.scwproject.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import com.zy.scwcommon.bean.AppResponse;
import com.zy.scwproject.component.OssTemplate;
import com.zy.scwproject.constant.ProjectConstant;
import com.zy.scwproject.entity.TReturn;
import com.zy.scwproject.vo.req.BaseVo;
import com.zy.scwproject.vo.req.ProjectBaseInfoVo;
import com.zy.scwproject.vo.req.ProjectRedisStorageVo;
import com.zy.scwproject.vo.req.ProjectReturnVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
 * @Description:项目的发布接口
 * @Param:
 * @return:
 * @Author: zy
 * @Date:
 */
@Api(tags = "项目发起模块")
@RequestMapping("/project/create")
@RestController
@Slf4j
public class ProjectCreateController {
    @Autowired
    OssTemplate ossTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;

    @ApiOperation(value = "1.项目初始创建")
    @PostMapping("/init")
    public AppResponse<Object> init(BaseVo baseVo) {
        try {
            String accessToken = baseVo.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                AppResponse fail = AppResponse.fail(null);
                fail.setMsg("请求必须提供accesstoken");
                return fail;
            }
            String access = redisTemplate.opsForValue().get(accessToken);
            if (StringUtils.isEmpty(access)) {
                AppResponse resp = AppResponse.fail(null);
                resp.setMsg("请先登陆系统，在发布项目");
                return resp;
            }
            ProjectRedisStorageVo bigVo = new ProjectRedisStorageVo();
            BeanUtils.copyProperties(baseVo, bigVo);
            String projectToken = UUID.randomUUID().toString().replace("-", "");//项目的projectToken
            bigVo.setProjectToken(projectToken);
            String jsonString = JSON.toJSONString(bigVo);
            redisTemplate.opsForValue().set(ProjectConstant.TEMP_PROJECT_PREFIX + projectToken, jsonString);//项目token===>bigvo的字符串---放到redis
            log.debug("bigvo:{}", bigVo);
            return AppResponse.ok(bigVo);
        } catch (BeansException e) {
            e.printStackTrace();
            return AppResponse.fail(null);
        }

    }

    @ApiOperation(value = "2-项目基本信息")
    @PostMapping("/baseinfo")
    public AppResponse<Object> baseinfo(ProjectBaseInfoVo vo) {
        try {
            //1.判断用户是否登录
            String accessToken = vo.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                AppResponse fail = AppResponse.fail(null);
                fail.setMsg("请求必须提供accesstoken");
                return fail;
            }
            String access = redisTemplate.opsForValue().get(accessToken);
            if (StringUtils.isEmpty(access)) {
                AppResponse resp = AppResponse.fail(null);
                resp.setMsg("请先登陆系统，在发布项目");
                return resp;
            }

            //2.在redis取出bigvo
            String bigstr = redisTemplate.opsForValue().get(ProjectConstant.TEMP_PROJECT_PREFIX + vo.getProjectToken());
            //把字符串转换成对象
            ProjectRedisStorageVo projectRedisStorageVo = JSON.parseObject(bigstr, ProjectRedisStorageVo.class);
            //3.把小vo复制到bigvo里去
            BeanUtils.copyProperties(vo, projectRedisStorageVo);
            //4.在把bigvo转换成字符串存入redis
            String bigVO = JSON.toJSONString(projectRedisStorageVo);
            redisTemplate.opsForValue().set(ProjectConstant.TEMP_PROJECT_PREFIX + vo.getProjectToken(), bigVO);
            log.debug("bigvo的数据=======", bigVO);
            return AppResponse.ok(bigVO);
        } catch (BeansException e) {
            e.printStackTrace();
            log.error("表单处理失败", e.getMessage());
            return AppResponse.fail(null);
        }
    }

    /*
    {
      "accessToken": "4adf9ca14a424de7ad5c81ad58bb9277",
      "day": 33,
      "detailsImage": [
        "one"
      ],
      "headerImage": "four",
      "money": 100000,
      "name": "投资好就有回报",
      "projectReturns": [
        {
          "content": "是的冯绍199峰大幅度发",
          "count": 1,
          "freight": 444455,
          "invoice": "1",
          "purchase": 3333,
          "rtndate": 66666,
          "signalpurchase": 0,
          "supportmoney": 199,
          "type": "string"
        },
        {
          "content": "是的冯绍299峰大幅度发",
          "count": 1,
          "freight": 666,
          "invoice": "5",
          "purchase": 77,
          "rtndate": 888,
          "signalpurchase": 0,
          "supportmoney": 399,
          "type": "string"
        },
        {
          "content": "很拼一的699====599",
          "count": 1,
          "freight": 888,
          "invoice": "5",
          "purchase": 999,
          "rtndate": 888,
          "signalpurchase": 1,
          "supportmoney": 599,
          "type": "string"
        }
      ],
      "projectToken": "4bd33e7f7f944dd98c4c4c173980b5bf",
      "remark": "加油",
      "tagids": [1],
      "typeids": [0]
    }
    上面是在postman的传参数的方式======
     */
    @ApiOperation(value = "3.添加项目回报档位")
    @PostMapping("/return")
    public AppResponse<Object> returnDetail(@RequestBody List<ProjectReturnVo> listreturns) {
        try {
            //1.判断用户是否登录
            String accessToken = listreturns.get(0).getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                AppResponse fail = AppResponse.fail(null);
                fail.setMsg("请求必须提供accesstoken");
                return fail;
            }
            String access = redisTemplate.opsForValue().get(accessToken);
            if (StringUtils.isEmpty(access)) {
                AppResponse resp = AppResponse.fail(null);
                resp.setMsg("请先登陆系统，在发布项目");
                return resp;
            }
            //2.在redis取出bigvo
            String bigstr = redisTemplate.opsForValue().get(ProjectConstant.TEMP_PROJECT_PREFIX + listreturns.get(0).getProjectToken());
            //把字符串转换成对象(bigvo)
            ProjectRedisStorageVo bigVO = JSON.parseObject(bigstr, ProjectRedisStorageVo.class);
            //3.把小vo复制到bigvo里去
            List<TReturn> projectReturns = bigVO.getProjectReturns();
            for (ProjectReturnVo listreturn : listreturns) {
                TReturn tReturn = new TReturn();
                BeanUtils.copyProperties(listreturn, tReturn);
                projectReturns.add(tReturn);
            }
            bigVO.setProjectReturns(projectReturns);
            String jsonString = JSON.toJSONString(bigVO);
            redisTemplate.opsForValue().set(ProjectConstant.TEMP_PROJECT_PREFIX + listreturns.get(0).getProjectToken(), jsonString);
            log.debug("======成功的数据=====", jsonString);
            return AppResponse.ok(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("错误的数据===", e.getMessage());
            return AppResponse.fail(null);
        }

    }

    @ApiOperation(value = "删除项目回报档位")
    @DeleteMapping("/return")
    public AppResponse<Object> deleteReturnDetail() {
        return AppResponse.ok("ok");
    }

    /**
     * @Author: zy 690748807@qq.com
     * @Param:
     * @return:
     * @Date: 2024/5/26  在postman测试
     * @Description: psot   localhost:8001/project/create/upload    body   form-data  fileupload---file
     */
    @ApiOperation(value = "上传图片")
    @PostMapping("/upload")
    public AppResponse<Object> upload(@RequestParam("fileupload") MultipartFile[] files) throws IOException {
        try {
            List<String> stringArrayList = new ArrayList<>();
            for (MultipartFile file : files) {
                String filepath = ossTemplate.upLoade(file.getOriginalFilename(), file.getInputStream());
                stringArrayList.add(filepath);
            }
            return AppResponse.ok(stringArrayList);
        } catch (Exception e) {
            e.printStackTrace();
            return AppResponse.fail(null);
        }
    }

    @ApiOperation(value = "确认项目法人信息")
    @PostMapping("/confirm/legal")
    public AppResponse<Object> legal() {

        return AppResponse.ok("ok");
    }

    @ApiOperation(value = "项目草稿保存")
    @PostMapping("/tempsave")
    public AppResponse<Object> tempsave() {
        return AppResponse.ok("ok");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "用户令牌", required = true),
            @ApiImplicitParam(name = "projectToken", value = "项目标识", required = true),
            @ApiImplicitParam(name = "ops", value = "用户操作类型   0-保存草稿   1-提交审核", required = true)
    })
    @ApiOperation("4.项目发起第4步-项目保存项目回报信息")
    @PostMapping("/submit")
    public AppResponse<Object> submit(String accessToken, String projectToken, String ops) {
        //1.判断用户是否登录
        //2.在redis取出bigvo
        //3.把小vo复制到bigvo里去
        //4.在把bigvo转换成字符串存入redis
        return AppResponse.ok("ok");
    }

}
